<template>
  <div v-if="pageStatus === 1">
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form ref="queryFormRef" :inline="true" :model="paramsData" class="-mb-10px" label-width="auto">
        <el-form-item label="事故编号" prop="code">
          <el-input v-model="paramsData.code" class="!w-280px" clearable placeholder="请输入事故编号"
            @keyup.enter="handleQuery" />
        </el-form-item>
  
        <el-form-item label="事故等级" prop="levelId">
          <el-select v-model="paramsData.levelId" filterable class="!w-280px" clearable placeholder="请选择事故等级">
            <el-option v-for="item in levelList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
  
        <el-form-item label="责任部门" prop="departmentId">
          <el-tree-select
            v-model="paramsData.departmentId"
            class="!w-280px"
            :data="deptTree"
            filterable
            clearable
            :props="defaultProps"
            check-strictly
            default-expand-all
            placeholder="请选择事故部门"
            value-key="deptId"
          />
        </el-form-item>
      
        <el-form-item label="事故状态" prop="status">
          <el-select v-model="paramsData.status" filterable class="!w-280px" clearable placeholder="请选择事故状态">
            <el-option v-for="item in statusList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="事故时间" prop="accidentTime">
          <el-date-picker
            v-model="paramsData.accidentTime"
            class="!w-280px"
            type="date"
            placeholder="请选择事故时间"
            @change="e => paramsData.accidentTime = formatDateToYMD(e)"
          />
        </el-form-item>

        <el-form-item label="应急预案" prop="emergencyId">
          <el-select v-model="paramsData.emergencyId" filterable class="!w-280px" clearable placeholder="请选择应急预案">
            <el-option v-for="item in emergencyList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button v-hasPermi="['wise:project:query']" @click="handleQuery">
            <Icon class="mr-5px" icon="ep:search" />
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon class="mr-5px" icon="ep:refresh" />
            重置
          </el-button>
          <el-button v-hasPermi="['wise:project:create']" plain type="primary" @click="openForm(1)">
            <Icon class="mr-5px" icon="ep:plus" />
            新增
          </el-button>
          <el-button v-hasPermi="['wise:project:export']" :loading="exportLoading" plain type="success"
            @click="handleExport">
            <Icon class="mr-5px" icon="ep:download" />
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
      <!-- 列表 -->
    <ContentWrap>
      <el-table v-loading="loading" :data="tableData" @selection-change="tableSelectionChange">
        <el-table-column type="selection" width="30" />
        <template v-for="item in tableColumn" :key="item.prop">
          <el-table-column
            :width="item.width"
            :align="item.align ? item.align : 'center'" 
            :label="item.label"
            :prop="item.prop"
          >
            <template #default="scope">
              <div v-if="item.prop === 'departmentId'">
                {{ findDeptNameById(deptTree, scope.row.departmentId) || '-' }}
              </div>
              <div v-else-if="item.prop === 'status'">
                <span>{{ statusList.find(item => item.id == scope.row.status)?.name || '-' }}</span>
              </div>
              <div v-else-if="item.prop === 'accidentTime'">{{ scope.row.accidentTime ? formatDate(scope.row.accidentTime) : '-' }}</div>
              <div v-else-if="item.prop == 'createTime'">
                <p>创建时间：{{ scope.row.createTime ? formatDate(scope.row.createTime) : '-' }}</p>
                <p>更新时间：{{ scope.row.updateTime ? formatDate(scope.row.updateTime) : '-' }}</p>
              </div>
              <div v-else-if="item.prop == 'creator'">
                <p>创建：{{ scope.row.creator || '-' }}</p>
                <p>更新：{{ scope.row.updater || '-' }}</p>
              </div>
              <div v-else>
                {{ scope.row[item.prop] || '-' }}
              </div>
            </template>
          </el-table-column>
        </template>

        <el-table-column :width="200" align="center" label="操作">
          <template #default="scope">
            <el-button v-hasPermi="['wise:project:update']" link type="primary" @click="openForm(2, scope.row.id)">
              <span v-if="scope.row.status === 1">编辑</span>
              <span v-else-if="scope.row.status === 2">处理</span>
              <span v-else>查看</span>
            </el-button>
            <el-button v-hasPermi="['wise:project:delete']" link type="danger" @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>


      <!-- 分页 -->
      <Pagination v-model:limit="paramsData.pageSize" v-model:page="paramsData.pageNo" :total="total" @pagination="getList" />
    </ContentWrap>
  </div>
  <AccidentForm v-else ref="formRef" />
</template>
<script setup>
  import { ref, nextTick, provide, reactive } from "vue"
  import { formatDate } from '@/utils/formatTime'
  import { formatDateToYMD } from '@/utils/index'
  import { defaultProps, handleTree } from '@/utils/tree'
  import * as DeptApi from '@/api/system/dept'
  import { levelList, statusList } from './jsonAndRules'
  import AccidentForm from './accidentForm.vue'
  const pageStatus = ref(1) // 1列表页  2新增编辑页
  const exportLoading = ref(false) // 导出的加载中
  const paramsData = reactive({
    code: '', // 事故编号
    levelId: '', // 等级Id
    departmentId: '', // 责任部门
    status: '', // 状态
    accidentTime: '', // 事故时间
    emergencyId: '', // 应急事故
    pageNum: 1,
    pageSize: 10,
    ids: [],
  })
  // 应急预案
  const emergencyList = ref([
    {
      id: 1, 
      code: '123', 
      name: '预案1', 
      type: '1', 
      leaderName: '张三', 
      departmentId: 103, 
      emergencyTime: 1758187445112,
      status: 1, 
      createTime: 1758187445000, 
      updateTime: 1748186445235, 
      creator: '张三',
      updater: '张三'
    },
    {
      id: 2, 
      code: '456', 
      name: '预案2', 
      type: '2', 
      leaderName: '李四', 
      departmentId: 100, 
      emergencyTime: 1758187445112,
      status: 0, 
      createTime: 1758187445000, 
      updateTime: 1748186445235, 
      creator: '李四',
      updater: '李四'
    },
  ])
  provide('emergencyList', emergencyList)
  const queryFormRef = ref() // 搜索表单
  const selectIds = ref([]) // 勾选的id
  const tableSelectionChange = (selection) => {
    selectIds.value = selection.map(item => item.id)
  }
  const loading = ref(false) // 列表的加载中
  const total = ref(0) // 列表的总页数

  const tableData = ref([
    {
      id: 1, 
      code: '123xxx', 
      levelName: '一般事故', 
      type: '1', 
      applytor: '张三', 
      departmentId: 103, 
      accidentTime: 1758187445112,
      status: 1, 
      emergencyName: '预案1',
      createTime: 1758187445000, 
      updateTime: 1748186445235, 
      creator: '张三（13887625983）',
      updater: '张三（13887625983）'
    },
    {
      id: 2, 
      code: '456xxxx', 
      levelName: '一般事故', 
      type: '2', 
      applytor: '李四', 
      departmentId: 100, 
      accidentTime: 1758187445112,
      status: 2, 
      emergencyName: '预案2',
      createTime: 1758187445000, 
      updateTime: 1748186445235, 
      creator: '张三（13887625983）',
      updater: '李四（13887625983）'
    },
    {
      id: 3, 
      code: '456xxxx', 
      levelName: '一般事故', 
      type: '3', 
      applytor: '李四', 
      departmentId: 110, 
      accidentTime: 1758187445112,
      status: 3, 
      emergencyName: '预案3',
      createTime: 1758187445000, 
      updateTime: 1748186445235, 
      creator: '张三（13887625983）',
      updater: '李四（13887625983）'
    },    
    {
      id: 4, 
      code: '456xxxx', 
      levelName: '一般事故', 
      type: '4', 
      applytor: '李四', 
      departmentId: 100, 
      accidentTime: 1758187445112,
      status: 4, 
      emergencyName: '预案4',
      createTime: 1758187445000, 
      updateTime: 1748186445235, 
      creator: '张三（13887625983）',
      updater: '李四（13887625983）'
    },
  ]) // 列表的数据
  const tableColumn = ref([
    { prop: 'code', label: '事故编号', align: 'center', width: 160},
    { prop: 'levelName', label: '事故等级', align: 'center', },
    { prop: 'applytor', label: '申报人', align: 'center', },
    { prop: 'departmentId', label: '责任部门', align: 'center'},
    { prop: 'accidentTime', label: '事故时间', align: 'center', width: 230},
    { prop: 'status', label: '事故状态', align: 'center'},
    { prop: 'emergencyName', label: '应急预案', align: 'center'},
    { prop: 'createTime', label: '时间', align: 'center', width: 230},
    { prop: 'creator', label: '操作人', align: 'center', width: 220},
  ]) // 表格的列
  const formRef = ref(null) // 新增、编辑页

  const getList = async () => {

  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    paramsData.pageNo = 1
    // getList()
  }
  /** 重置按钮操作 */
  const resetQuery = () => {
    paramsData.leaderName = ''
    queryFormRef.value.resetFields()
    handleQuery()
  }
  const goBack = () => {
    pageStatus.value = 1
    // getList()
  }
  provide('goBack', goBack)
  const openForm = (id) => {
    pageStatus.value = 2
    nextTick(() => {
      formRef.value.init(id)
    })
  }
  const handleExport = async () => {
    if(selectIds.value.length > 0){
      paramsData.ids = selectIds.value
    }
    try {
      // 导出的二次确认
      await message.exportConfirm()
      // 发起导出
      exportLoading.value = true
      const data = await ProjectApi.exportProject(paramsData)
      download.excel(data, '项目管理列表.xls')
    } catch {
    } finally {
      exportLoading.value = false
    }
  }
  onMounted( async () => {
    await getTree()
    await getList()
  })
  const deptTree = ref() // 树形结构
  provide('deptTree', deptTree)
  /** 获得部门树 */
  const getTree = async () => {
    deptTree.value = []
    const data = await DeptApi.getSimpleDeptList()
    deptTree.value = handleTree(data)
  }
  function findDeptNameById(tree, id) {
    let nodeName = '-'
    for (const node of tree) {
      if (node.id === id) {
        nodeName = node.name
      }
      if(nodeName !== '-'){
        return nodeName
      }
      if(node.children && node.children.length > 0){
        nodeName = findDeptNameById(node.children, id)
      }
    }
    return nodeName
  }
  provide('findDeptNameById', findDeptNameById)
</script>
<style lang="scss" scoped>

</style>
